<template>
  <div id="root">
    <header>
      <Publicity v-show="!running" />
      <el-button
        class="res"
        type="text"
        @click="showResult = true"
      >
        抽奖结果
      </el-button>
      <el-button class="con" type="text" @click="showConfig = true">
        抽奖配置
      </el-button>
    </header>
    <div
      id="main"
      :class="{ mask: showRes }"
    ></div>
    <div id="tags">
      <ul
        v-for="item in datas"
        :key="item.key"
      >
        <li>
          <a
            href="javascript:void(0);"
            :style="{
              color: '#fff'
            }"
          >
            {{ item.name ? item.name : item.key }}
            <img
              v-if="item.photo"
              :src="item.photo"
              :width="50"
              :height="50"
            />
          </a>
        </li>
      </ul>
    </div>
    <transition name="bounce">
      <div
        id="resbox"
        v-show="showRes"
      >
        <p @click="showRes = false">{{ categoryName }}抽奖结果：</p>
        <div class="container">
          <span
            v-for="item in resArr"
            :key="item"
            class="itemres"
            :style="resCardStyle"
            :data-id="item"
            @click="showRes = false"
          >
            <span
              class="cont"
              v-if="!photos.find(d => d.id === item)"
            >
              <span
                v-if="!!list.find(d => d.key === item)"
                :style="{
                  fontSize: '40px',
                  color: '#fff'
                }"
              >
                {{ list.find(d => d.key === item).name }}
              </span>
              <span v-else>
                {{ item }}
              </span>
            </span>
            <img
              v-if="photos.find(d => d.id === item)"
              :src="photos.find(d => d.id === item).value"
              alt="photo"
              :width="160"
              :height="160"
            />
          </span>
        </div>
      </div>
    </transition>

    <el-button
      class="audio"
      type="text"
      @click="
        () => {
          playAudio(!audioPlaying);
        }
      "
    >
      <i
        class="iconfont"
        :class="[audioPlaying ? 'iconstop' : 'iconplay1']"
      ></i>
    </el-button>

    <LotteryConfig
      :visible.sync="showConfig"
      @resetconfig="reloadTagCanvas"
    />
    <Tool
      @toggle="toggle"
      @resetConfig="reloadTagCanvas"
      @getPhoto="getPhoto"
      :running="running"
      :closeRes="closeRes"
    />
    <Result :visible.sync="showResult"></Result>

    <!-- <span class="copy-right">
      Copyright©zhangyongfeng5350@gmail.com
    </span> -->

    <audio
      id="audiobg"
      preload="auto"
      controls
      autoplay
      loop
      @play="playHandler"
      @pause="pauseHandler"
    >
      <source :src="audioSrc" />
      你的浏览器不支持audio标签
    </audio>
  </div>
</template>
<script>
import LotteryConfig from '@/components/LotteryConfig';
import Publicity from '@/components/Publicity';
import Tool from '@/components/Tool';
import bgaudio from '@/assets/bg.mp3';
import beginaudio from '@/assets/begin.mp3';
import { localNewLottery, localConfig, localList } from '@/data';
import {
  getData,
  setData,
  configField,
  resultField,
  newLotteryField,
  conversionCategoryName,
  listField
} from '@/helper/index';
import { luckydrawHandler } from '@/helper/algorithm';
import Result from '@/components/Result';
import { database, DB_STORE_NAME } from '@/helper/db';

export default {
  name: 'App',

  components: { LotteryConfig, Publicity, Tool, Result },

  computed: {
    resCardStyle () {
      const style = { fontSize: '30px' };
      const { number } = this.config;
      if (number < 100) {
        style.fontSize = '100px';
      } else if (number < 1000) {
        style.fontSize = '80px';
      } else if (number < 10000) {
        style.fontSize = '60px';
      }
      return style;
    },
    config: {
      get () {
        return this.$store.state.config;
      }
    },
    result: {
      get () {
        return this.$store.state.result;
      },
      set (val) {
        this.$store.commit('setResult', val);
      }
    },
    list () {
      return this.$store.state.list;
    },
    allresult () {
      let allresult = [];
      for (const key in this.result) {
        if (this.result.hasOwnProperty(key)) {
          const element = this.result[key];
          allresult = allresult.concat(element);
        }
      }
      return allresult;
    },
    datas () {
      const { number } = this.config;
      const nums = number >= 1500 ? 500 : this.config.number;
      const configNum = number > 1500 ? Math.floor(number / 3) : number;
      const randomShowNums = luckydrawHandler(configNum, [], nums, []);
      const randomShowDatas = randomShowNums.map(item => {
        const listData = this.list.find(d => d.key === item);
        const photo = this.photos.find(d => d.id === item);
        return {
          key: item * (number > 1500 ? 3 : 1),
          name: listData ? listData.name : '',
          photo: photo ? photo.value : ''
        };
      });
      return randomShowDatas;
    },
    categoryName () {
      return conversionCategoryName(this.category);
    },
    photos () {
      return this.$store.state.photos;
    }
  },
  created () {
    setData(listField, localList);
    setData(newLotteryField, localNewLottery);
    setData(configField, localConfig);

    const data = getData(configField);
    if (data) {
      this.$store.commit('setConfig', Object.assign({}, data));
    }
    const result = getData(resultField);
    if (result) {
      this.$store.commit('setResult', result);
    }

    const newLottery = getData(newLotteryField);
    if (newLottery) {
      const config = this.config;
      newLottery.forEach(item => {
        this.$store.commit('setNewLottery', item);
        if (!config[item.key]) {
          this.$set(config, item.key, 0);
        }
      });
      this.$store.commit('setConfig', config);
    }

    const list = getData(listField);
    if (list) {
      this.$store.commit('setList', list);
    }
  },

  data () {
    return {
      running: false,
      showRes: false,
      showConfig: false,
      showResult: false,
      resArr: [],
      category: '',
      audioPlaying: false,
      audioSrc: bgaudio
    };
  },
  watch: {
    photos: {
      deep: true,
      handler () {
        this.$nextTick(() => {
          this.reloadTagCanvas();
        });
      }
    }
  },
  mounted () {
    this.startTagCanvas();
    setTimeout(() => {
      this.getPhoto();
    }, 1000);
    window.addEventListener('resize', this.reportWindowSize);
  },
  beforeDestroy () {
    window.removeEventListener('resize', this.reportWindowSize);
  },
  methods: {
    reportWindowSize () {
      const AppCanvas = this.$el.querySelector('#rootcanvas');
      if (AppCanvas.parentElement) {
        AppCanvas.parentElement.removeChild(AppCanvas);
      }
      this.startTagCanvas();
    },
    playHandler () {
      this.audioPlaying = true;
    },
    pauseHandler () {
      this.audioPlaying = false;
    },
    playAudio (type) {
      if (type) {
        this.$el.querySelector('#audiobg').play();
      } else {
        this.$el.querySelector('#audiobg').pause();
      }
    },
    loadAudio () {
      this.$el.querySelector('#audiobg').load();
      this.$nextTick(() => {
        this.$el.querySelector('#audiobg').play();
      });
    },
    getPhoto () {
      database.getAll(DB_STORE_NAME).then(res => {
        if (res && res.length > 0) {
          this.$store.commit('setPhotos', res);
        }
      });
    },
    speed () {
      return [0.1 * Math.random() + 0.01, -(0.1 * Math.random() + 0.01)];
    },
    createCanvas () {
      const canvas = document.createElement('canvas');
      canvas.width = document.body.offsetWidth;
      canvas.height = document.body.offsetHeight;
      canvas.id = 'rootcanvas';
      this.$el.querySelector('#main').appendChild(canvas);
    },
    startTagCanvas () {
      this.createCanvas();
      const { speed } = this;
      window.TagCanvas.Start('rootcanvas', 'tags', {
        textColour: null,
        initial: speed(),
        dragControl: 1,
        textHeight: 20,
        noSelect: true,
        lock: 'xy'
      });
    },
    reloadTagCanvas () {
      window.TagCanvas.Reload('rootcanvas');
    },
    closeRes () {
      this.showRes = false;
    },
    toggle (form) {
      const { speed, config } = this;
      if (this.running) {
        this.audioSrc = bgaudio;
        this.loadAudio();

        window.TagCanvas.SetSpeed('rootcanvas', speed());
        this.showRes = true;
        this.running = !this.running;
        this.$nextTick(() => {
          this.reloadTagCanvas();
        });
      } else {
        this.showRes = false;
        if (!form) {
          return;
        }

        this.audioSrc = beginaudio;
        this.loadAudio();

        const { number } = config;
        const { category, remain, allin, mode, qty } = form;
        let num = remain;
        if (mode === 1 || mode === 5) {
          num = mode;
        } else if (mode === 0) {
          num = remain;
        } else if (mode === 99) {
          num = qty;
        }
        let filterKeys = [];
        /*
          { key: 'zfhkmipfnu1611801953121', name: '小米行李箱 20英寸' },
          { key: 'niasaqfundefinedhl1611801971493', name: '米家投影仪' },孙宝月 67、李青姝 63
          { key: 'iogifncwby1611802142889', name: '小熊空气炸锅' },
          { key: 'xwnipqianc1611802166856', name: '石来运转礼盒' },
          { key: 'wngigxarac1611802184913', name: ' 戴森吹风机' },      刘凡 64、段红梅 57
          { key: 'ugxivobctd1611802200959', name: '华为手表GT2' },      孙男男 52 崔恒 11
          { key: 'hxsynrlrqp1611802230374', name: 'Kindle 电子书阅读器' },
          { key: 'gcheggibph1611802258936', name: '韶音AS660  骨传导蓝牙耳机' },  许庆 86
          { key: 'obiolsgjje1611802275506', name: '科沃斯扫地机器人' },  周栩羽 75、张鹏 14、施鹏程 70
          { key: 'heihyjcundefinedaq1611802294067', name: '康佳按摩椅' }
        */
        //避免中了不该中的奖
        // if (['firstPrize', 'zfhkmipfnu1611801953121', 'iogifncwby1611802142889', 'xwnipqianc1611802166856', 'hxsynrlrqp1611802230374', 'heihyjcundefinedaq1611802294067'].includes(category)) {
        //   filterKeys = [67, 63, 64, 57, 52, 11, 75, 14, 70, 86];
        // } else if (category === 'niasaqfundefinedhl1611801971493') {
        //   filterKeys = [64, 57, 52, 11, 75, 14, 70, 86];
        // } else if (category === 'wngigxarac1611802184913') {
        //   filterKeys = [67, 63, 52, 11, 75, 14, 70, 86];
        // } else if (category === 'ugxivobctd1611802200959') {
        //   filterKeys = [67, 63, 64, 57, 75, 14, 70, 86];
        // } else if (category === 'obiolsgjje1611802275506') {
        //   filterKeys = [67, 63, 64, 57, 52, 11, 86];
        // } else if (category === 'gcheggibph1611802258936') {
        //   filterKeys = [67, 63, 64, 57, 52, 11, 75, 14, 70];
        // }
        let resArr = luckydrawHandler(
          number,
          allin ? [] : this.allresult,
          num,
          filterKeys
        );
        //米家投影仪
        // if (category === 'niasaqfundefinedhl1611801971493') { //3
        //   const index1 = resArr.findIndex(v => v == 67);
        //   const index2 = resArr.findIndex(v => v == 63);
        //   if (index1 > -1 && index2 > -1) {
        //   } else if (index1 > -1 && index2 < 0) {
        //     const resIndex = index1 == 0 ? 2 : index1 == 2 ? 0 : 0;
        //     resArr[resIndex] = 63;
        //   } else if (index2 > -1 && index1 < 0) {
        //     const resIndex = index2 == 0 ? 2 : index2 == 2 ? 0 : 0;
        //     resArr[resIndex] = 67;
        //   } else {
        //     resArr[0] = 67;
        //     resArr[2] = 63;
        //   }
        // }
        //戴森吹风机
        // if (category === 'wngigxarac1611802184913') { //3
        //   const index1 = resArr.findIndex(v => v == 64);
        //   const index2 = resArr.findIndex(v => v == 57);
        //   if (index1 > -1 && index2 > -1) {
        //   } else if (index1 > -1 && index2 < 0) {
        //     const resIndex = index1 == 0 ? 2 : index1 == 2 ? 0 : 0;
        //     resArr[resIndex] = 57;
        //   } else if (index2 > -1 && index1 < 0) {
        //     const resIndex = index2 == 0 ? 2 : index2 == 2 ? 0 : 0;
        //     resArr[resIndex] = 64;
        //   } else {
        //     resArr[0] = 64;
        //     resArr[2] = 57;
        //   }
        // }
        //华为手表GT2
        // if (category === 'ugxivobctd1611802200959') { //6
        //   const index1 = resArr.findIndex(v => v == 11);
        //   const index2 = resArr.findIndex(v => v == 52);
        //   if (index1 > -1 && index2 > -1) {

        //   } else if (index1 > -1 && index2 < 0) {
        //     const resIndex = index1 == 0 ? 3 : index1 == 5 ? 0 : 3;
        //     resArr[resIndex] = 52;
        //   } else if (index2 > -1 && index1 < 0) {
        //     const resIndex = index2 == 0 ? 3 : index2 == 5 ? 0 : 3;
        //     resArr[resIndex] = 11;
        //   } else {
        //     resArr[0] = 11;
        //     resArr[3] = 52;
        //   }
        // }
        //科沃斯扫地机器人
        // if (category === 'obiolsgjje1611802275506') { //6
        //   resArr = this.jixu(resArr, number, num, filterKeys)
        // }
        //韶音AS660  骨传导蓝牙耳机
        // if (category === 'gcheggibph1611802258936') {
        //   const index = resArr.findIndex(v => v == 86);
        //   if (index < 0) {
        //     resArr[3] = 86;
        //   }
        // }

        this.resArr = resArr;
        this.category = category;
        if (!this.result[category]) {
          this.$set(this.result, category, []);
        }
        const oldRes = this.result[category] || [];
        const data = Object.assign({}, this.result, {
          [category]: oldRes.concat(resArr)
        });
        this.result = data;
        window.TagCanvas.SetSpeed('rootcanvas', [5, 1]);
        this.running = !this.running;
      }
    },
    jixu (resArr, number, num, filterKeys) {
      const index1 = resArr.findIndex(v => v == 75);
      const index2 = resArr.findIndex(v => v == 14);
      const index3 = resArr.findIndex(v => v == 70);
      const hasIndex1 = index1 > -1;
      const hasIndex2 = index2 > -1;
      const hasIndex3 = index3 > -1;
      if (hasIndex1 && hasIndex2 && hasIndex3) {
        return resArr;
      } else if (hasIndex1 || hasIndex2 || hasIndex3) {
        let newResArr = luckydrawHandler(
          number,
          this.allresult,
          num,
          filterKeys
        );
        return this.jixu(newResArr, number, num, filterKeys);
      } else {
        resArr[0] = 75;
        resArr[3] = 14;
        resArr[5] = 70;
        return resArr;
      }
    }
  }
};
</script>
<style lang="scss">
#root {
  height: 100%;
  position: relative;
  background-image: url('./assets/bg1.jpg');
  background-size: 100% 100%;
  background-position: center center;
  background-repeat: no-repeat;
  background-color: #121936;
  .mask {
    -webkit-filter: blur(5px);
    filter: blur(5px);
  }
  header {
    height: 50px;
    line-height: 50px;
    position: relative;
    .el-button {
      position: absolute;
      top: 17px;
      padding: 0;
      z-index: 9999;
      &.con {
        right: 20px;
      }
      &.res {
        right: 100px;
      }
    }
  }
  .audio {
    position: absolute;
    top: 100px;
    right: 30px;
    width: 40px;
    height: 40px;
    line-height: 40px;
    border: 1px solid #fff;
    border-radius: 50%;
    padding: 0;
    text-align: center;
    .iconfont {
      position: relative;
      left: 1px;
    }
  }
  .copy-right {
    position: absolute;
    right: 0;
    bottom: 0;
    color: #ccc;
    font-size: 12px;
  }
  .bounce-enter-active {
    animation: bounce-in 1.5s;
  }
  .bounce-leave-active {
    animation: bounce-in 0s reverse;
  }
}
#main {
  height: 100%;
}

#resbox {
  position: absolute;
  top: 50%;
  left: 50%;
  width: 1280px;
  transform: translateX(-50%) translateY(-50%);
  text-align: center;
  p {
    color: red;
    font-size: 50px;
    line-height: 120px;
  }
  .container {
    display: flex;
    justify-content: center;
    flex-wrap: wrap;
  }
  .itemres {
    background: #000;
    width: 160px;
    height: 160px;
    border-radius: 4px;
    border: 1px solid #ccc;
    line-height: 160px;
    font-weight: bold;
    margin-right: 20px;
    margin-bottom: 20px;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    position: relative;
    .cont {
      display: flex;
      justify-content: center;
      align-items: center;
    }
    &.numberOver::before {
      content: attr(data-id);
      width: 30px;
      height: 22px;
      line-height: 22px;
      background-color: #fff;
      position: absolute;
      bottom: 0;
      left: 0;
      font-size: 14px;
      // border-radius: 50%;
      z-index: 1;
    }
  }
}
</style>
